import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import fetch from 'API/fetch';
import { Spin } from 'antd';
import dayjs from 'dayjs';
import ResponseTime from './ResponseTime';
import Availability from './Availability';
import AbnormalState from './AbnormalState';
import s from './style.module.css';
import resultNumbers from '../resultNumbers';
import Datetime from '@knownsec/react-component/dist/Datetime'
import moment from 'moment'
import { cloneDeep } from 'lodash'
const TIME = 24 * 60 * 60 * 1000;
const emptyData = (st, et) => {
	return [
		{
			aviliable: [{ area: '暂无数据', totalTime: 0 }],
			datetime: st,
			id: 'empty',
		},
		{
			aviliable: [{ area: '暂无数据', totalTime: 0 }],
			datetime: et,
			id: 'empty',
		},
	];
};
class Monitor extends React.PureComponent {
	static propTypes = {
		className: PropTypes.string,
		taskType: PropTypes.string,
		jobId: PropTypes.string,
		target: PropTypes.string,
		data: PropTypes.shape({
			results: PropTypes.arrayOf(
				PropTypes.shape({
					datetime: PropTypes.date,
				})
			),
		}),
	};

	static defaultProps = {
		className: '',
	};

	state = {
		loading: true,
		results: [],
		emptyData: emptyData(
			new Date(new Date().getTime() - 1 * TIME).toISOString(),
			new Date().toISOString()
		),
		dateStr: '今天',
		minDate: JSON.parse(sessionStorage.getItem('resD'))?.balance?.aviliableMaxHistory?.total || 60,
		dateRange: [moment().startOf('day'), moment().endOf('day')],
		isClose: true
	};

	setFilter = val => {
		this.setState({ filter: val });
	};

	handleSelectToday = v => {
		this.setState({
			dateStr: '今天',
			dateRange: [moment().startOf('day'), moment().endOf('day')],
		}, () => {
			this.getData()
		})
	};

	handleDateChange = dateRange => {
		this.setState({ dateRange: dateRange || [], dateStr: undefined });
		if (!dateRange) {
			this.handleSelectToday(1);
		}
		if (dateRange.length === 2) {
			this.getData(dateRange);
		}
	};

	handleSelectYesterday = () => {
		this.setState({
			dateStr: '昨天',
			dateRange: [moment().subtract(1, 'd').startOf('day'), moment().subtract(1, 'd').endOf('day')],
		}, () => {
			this.getData();
		});
	};

	getData = async date => {
		let [st, et] = this.state.dateRange
		st = st.startOf('day').toISOString()
		et = et.endOf('day').toISOString()
		this.setState({ emptyData: emptyData(st, et), loading: true });
		const target=encodeURIComponent(this.props.target)
		const url = `/api/v2/repodatas/report-task?jobId=${this.props.jobId}&taskType=${this.props.taskType}&range=range&target=${target}&startTime=${st}&endTime=${et}`;
		const res = await fetch(url, {
			method: 'GET',
		}).catch(() => this.setState({ results: [] }));
		const restt = resultNumbers(res.TaskData).map(item => {
			item.datetime = moment(item.datetime).format('YYYY-MM-DD HH:mm:ss')
			return item
		});
		this.setState({ results: restt, loading: false });
	};
	timeClose = open => {
		this.setState({ isClose: !open }, () => {
			if (!open && this.state.dateRange.length === 2) {
				const [st, et] = cloneDeep(this.state.dateRange)
				let dateStr = ''
				if (st.unix() === moment().startOf('day').unix() && et.unix() === moment().endOf('day').unix()) {
					dateStr = '今天'
				}
				if (st.unix() === moment().subtract(1, 'd').startOf('day').unix() && et.unix() === moment().subtract(1, 'd').endOf('day').unix()) {
					dateStr = '昨天'
				}
				this.setState({
					dateStr,
					dateRange: [st, et]
				}, () => {
					this.getData()
				})
			}
		})
	}
	componentDidMount() {
		this.getData();
	}

	render() {
		const {
			className,
			taskType,
			// data: { results },
		} = this.props;
		const { dateStr, dateRange, results, loading, minDate } = this.state;

		// const initResult = results.filter(item => {
		// 	const date = new Date(item.datetime);
		// 	return date >= dateRange.startTime && date <= dateRange.endTime;
		// });

		const disableDate = (current) => {
			return current.diff(moment(), 'days', true) >= 0
				|| current.diff(moment().subtract(minDate > 60 ? 60 : minDate, 'days'), 'days', true) <= 0;
		 }
		return (
			<div className={cn(className, s.monitor)}>
				<Spin spinning={loading}>
					<div className={s.selectContainer}>
						<div className={cn(className, s.raskSelect)}>
							<div
								className={cn(s.speBtn, {
									[s.active]: dateStr === '今天',
								})}
								onClick={() => this.handleSelectToday(1)}
							>
								今天
							</div>
							<div
								className={cn(s.speBtn, {
									[s.active]: dateStr === '昨天',
								})}
								onClick={this.handleSelectYesterday}
							>
								昨天
							</div>
							<Datetime
								value={dateRange}
								allowClear={false}
								disabledDate={disableDate}
								onOpenChange={this.timeClose}
								style={{marginLeft: '10px'}}
								onChange={(val, str) => {
									const dateR = cloneDeep(val)
									if (dateR.length === 2) {
										const st = cloneDeep(val[0]).startOf('day')
										const maxEndDay = st.add(7, 'd').endOf('day')
										if (dateR[1].endOf('day').unix() > maxEndDay.unix()) {
											dateR[1] = maxEndDay
										}
									}
									this.setState({ dateRange: dateR })
								}}
								showTime={false} ranges={{}}  />
							{/* <DateRange
								className={s.dateRange}
								onChange={this.handleDateChange}
								value={dateRange}
								showClearDates={true}
								maxDay={60}
							/> */}
						</div>
					</div>
					<ResponseTime
						resultNumbers={results.length ? results : this.state.emptyData}
						keyStr={`${dateStr}`}
					/>
					<div className={s.chartContainer}>
						<Availability
							dateStr={`${dateStr}`}
							className={s.availability}
							resultNumbers={results}
						/>
						<AbnormalState
							className={s.abnormal}
							dateStr={`${dateStr}`}
							resultNumbers={results}
						/>
					</div>
				</Spin>
			</div>
		);
	}
}

export default Monitor;
